package com.learning.security.core;

import com.learning.security.dal.dataobject.MenuDO;
import com.learning.security.dal.dataobject.RoleDO;
import com.learning.security.service.MenuService;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Component
public class CustomSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    private final MenuService menuService;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public CustomSecurityMetadataSource(MenuService menuService) {
        this.menuService = menuService;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestURI = ((FilterInvocation) object).getRequest().getRequestURI();
        List<MenuDO> menuDOList = menuService.getAllMenu();
        for (MenuDO menuDO : menuDOList) {
            if (antPathMatcher.match(menuDO.getPattern(), requestURI)) {
                String[] roles = menuDO.getRoles().stream().map(RoleDO::getName).toArray(String[]::new);
                return SecurityConfig.createList(roles);
            }
        }
        return Collections.emptyList();
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return Collections.emptyList();
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
